package servlet.admin;

import com.google.gson.Gson;
import entity.Apply;
import service.ApplyService;
import service.Impl.ApplyServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

//@WebServlet(urlPatterns = "/admin/ApplyFinByState")
//public class ApplyFinByStateServlet extends HttpServlet {
//    private ApplyService applyService = new ApplyServiceImpl();
//
//    @Override
//    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        Integer state = Integer.parseInt(req.getParameter("state"));
//        req.setAttribute("state",applyService.findByState(state));
//        resp.sendRedirect(req.getContextPath()+"/admin/ApplyList");
//    }
//}
//@WebServlet(urlPatterns = "/admin/ApplySearch")
//public class ApplyFinByStateServlet extends HttpServlet {
//    private ApplyService applyService = new ApplyServiceImpl();
//
//    @Override
//    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        resp.setContentType("application/json;charset=UTF-8");
//        resp.setCharacterEncoding("UTF-8");
//
//        String state = req.getParameter("state");
//        List<Apply> applies = applyService.findByState(Integer.parseInt(state));
//        PrintWriter out = resp.getWriter();
//        out.print(new Gson().toJson(applies));
//        out.flush();
//    }
//}
@WebServlet(urlPatterns = "/admin/ApplySearch")
public class ApplyFinByStateServlet extends HttpServlet {
    private ApplyService applyService = new ApplyServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");

        String stateStr = req.getParameter("state");
        List<Apply> applies;

        if (stateStr == null || stateStr.trim().isEmpty() || "all".equals(stateStr)) {
            // 如果state为空或者为"all"，查询所有记录
            applies = applyService.findAll();
        } else {
            try {
                Integer state = Integer.parseInt(stateStr);
                applies = applyService.findByState(state);
            } catch (NumberFormatException e) {
                // 如果state不是有效的整数，返回错误信息
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                PrintWriter out = resp.getWriter();
                out.print("{\"error\":\"Invalid state parameter\"}");
                out.flush();
                return;
            }
        }

        PrintWriter out = resp.getWriter();
        out.print(new Gson().toJson(applies));
        out.flush();
    }
}